import { loadrObj } from "@/components/loading/Loading";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";

const gltfLoader = new GLTFLoader();
let model = "";
let startSeconds;
let curSeconds;

const simulateLoad = (callback) => {
  let loaded = 0;
  let total = 100;
  var t = setInterval(() => {
    loaded = loaded + 1;
    // curSeconds = new Date().getSeconds();
    let progress = (loaded / total) * 100;
    loadrObj.loadingProgress = progress > 100 ? 100 : progress;
    // if (loadrObj.loadingProgress > 95) {
      // console.log("loader-res", loadrObj.loadingProgress);
      // console.log("loader-model", model);
    // }
    if (model && loadrObj.loadingProgress > 99) {
      clearInterval(t);
      callback("end");
    } else {
      callback("progress");
    }
  }, 0);
};

export const loadGLTF = (url: string) => {
  model = "";
  // startSeconds = new Date().getSeconds();
  loadrObj.isShow = true;
  return new Promise((resolve, reject) => {
    simulateLoad((res) => {
      // console.log("seconds", startSeconds, curSeconds);
      if (res == "end" && model) {
        loadrObj.isShow = false;
        // console.log(
        //   "回调模型--------------------------",
        //   new Date().getMinutes() + "分" + new Date().getSeconds() + "秒"
        // );
        resolve(model);
      } 
      // else if (curSeconds - startSeconds > 5) {
      //   // 刷新页面
      //   window.location.reload();
      // }
    });
    // console.log(
    //   "开始加载--------------------------",
    //   new Date().getMinutes() + "分" + new Date().getSeconds() + "秒"
    // );

    gltfLoader.load(
      url,
      (object: any) => {
        model = object;
        // console.log(
        //   "结束加载拿到模型--------------------------",
        //   new Date().getMinutes() + "分" + new Date().getSeconds() + "秒"
        // );
      },
      (xhr) => {
        // 监听加载过程
        // if ((xhr.loaded / xhr.total) * 100 < 100) {
        //   loadrObj.loadingProgress = (xhr.loaded / xhr.total) * 100;
        // } else {
        //   loadrObj.loadingProgress = 99;
        // }
        // console.log((xhr.loaded / xhr.total) * 100 + "% 已加载");
      },
      (error: any) => {
        reject(error);
      }
    );
  });
};

export const removeGLTF = (url: string) => {};
